package io;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.*;

/**
 * @author Mr.Sun
 * @date 2022年09月02日 11:21
 *
 * 使用zip进行多文件保存
 * {args: src/io/ZipCompress.java}
 */
public class ZipCompress {
    public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("test.zip");
        CheckedOutputStream cos = new CheckedOutputStream(fos, new Adler32());
        ZipOutputStream zos = new ZipOutputStream(cos);
        BufferedOutputStream out = new BufferedOutputStream(zos);
        // 只有setComment()，没有getComment()
        zos.setComment("A test of Java Zipping");
        for(String arg : args) {
            System.out.println("Writing file " + arg);
            BufferedReader in = new BufferedReader(new FileReader(arg));
            zos.putNextEntry(new ZipEntry(arg));
            int c;
            while((c = in.read()) != -1)
                out.write(c);
            in.close();
            out.flush();
        }
        out.close();
        // 校验和仅在文件关闭后有效！
        System.out.println("Checksum: " + cos.getChecksum().getValue());

        // 现在提取文件
        System.out.println("Reading file");
        FileInputStream fi = new FileInputStream("test.zip");
        CheckedInputStream cis = new CheckedInputStream(fi, new Adler32());
        ZipInputStream in2 = new ZipInputStream(cis);
        BufferedInputStream bis = new BufferedInputStream(in2);
        ZipEntry ze;
        while((ze = in2.getNextEntry()) != null) {
            System.out.println("Reading file " + ze);
            int x;
            while((x = bis.read()) != -1) {
                System.out.write(x);
            }
        }
        if(args.length == 1) {
            System.out.println("Checksum: " + cis.getChecksum().getValue());
        }

        bis.close();
        // Alternative way to open and read Zip files:
        ZipFile zf = new ZipFile("test.zip");
        Enumeration e = zf.entries();
        while(e.hasMoreElements()) {
            ZipEntry ze2 = (ZipEntry)e.nextElement();
            System.out.println("File: " + ze2);
        }
    }
}
